package BeautNum::AAImage;

use strict;
use warnings;

# this is a hack for the moment call as follows
#   perl -Ilib -e 'use BeautNum::AAImage; BeautNum::AAImage->draw(-imageUrl =>
#   "../BeautifulNumber/michael_bigger.jpg")'

# TODO use File::Slurp or similar to read the URL into string to Ascii art it
# maybe http://www.perlmonks.org/?node_id=1952

# this is specific to a server some place where Image::Caa was successfully
# installed
use lib '/home/micsar/myperl/share/perl/5.8.4/';
use Image::Caa;
use Image::Magick;
use Term::ReadKey;

sub draw {
    my $class = shift;
    my %args = (@_);
    my $cols = delete $args{-cols};
    my $lines = delete $args{-lines};
    my $imageUrl = delete $args{-imageUrl};
    eval {($cols, $lines) = GetTerminalSize()};# unless ($cols && $lines);
    if ($@) {
        warn 'failed to get terminal size setting to default';
        ($cols, $lines) = (80, 50);
    }

    # load an image

    my $image = Image::Magick->new;
    #$image->Read('37040513_3e3f6318b5.jpg');
    #$image->Read('michael_bigger.jpg');
    #$image->Read('244.1234567890.gif');
    $image->Read($imageUrl);
    my ($imageW, $imageH) = $image->Get('width', 'height');
    my ($aaW, $aaH);
    if ($imageH - $lines >= $imageW - $cols) {
        $aaH = $lines;
        $aaW = $cols * $lines / $imageH;
    }
    else {
        $aaH = $lines * $cols / $imageW;
        $aaW = $cols;
    }
    warn sprintf 'height is %s width is %s for image %s x %s on %s x %s', $aaH, $aaW, $imageH, $imageW, $lines, $cols;
    $aaW = 50;
    $aaH = 20;
    $aaW = $aaW * 4.6; # offset for character width to height

    # display it as ASCII Art

    my $caa = new Image::Caa();
    #$caa->draw_bitmap(0, 0, $aaW, $aaH, $image);

    # some fancy options
    $caa = new Image::Caa(
        driver => 'DriverANSI',
        dither => 'DitherOrdered8',
        black_bg => 1,
    );
    $caa->draw_bitmap(0, 0, $aaW, $aaH, $image)
}

1;
